import json

import requests

import loadInterData
from foodSqlDao import FoodDao
from faker import Faker

fake = Faker('zh_CN')
foodDao = FoodDao()
dataInter = loadInterData.load_inter_df(header=["userID", "itemID", "rating"], datapath="../interData/data.csv",
                                        sep=',',
                                        has_header=True)
# # 获取数据集的行数和列数
num_rows = dataInter.shape[0]
num_cols = dataInter.shape[1]

# 读取JSON文件
# num=0
# for x in range(10):
#     with open('foodJsonData/foodStoreData'+str(x)+'.json', 'r',encoding='UTF-8') as f:
#         data = json.load(f)
#         num=num+len(data)
indicesStyle1 = [8, 9, 10]  # 文件后缀索引-------------- 0, 1, 2, 3, 4, 5, 6, 7,
indexFileData = 0  # 当前读到第几个文件
fileNamePrefix = 'foodStoreDataVirtual'  # 'foodStoreData'  # foodStoreDataVirtual 文件前缀--------

lastRowIndex = None  # 交互数据读取到第几行索引的时候 没有foodData数据了 这个索引是从0开始的

foodStoreData = []  # 读取一个文件所得到的foodData数据

errorProductList = list()  # 那些itemID插入系统失败
errorProductCommentList = list()  # 那些itemID的评论插入系统失败
# # 打印数据集的行数和列数
print("该数据集共有{}行，{}列。".format(num_rows, num_cols))
for row_index in range(11260, num_rows):  # 第一个索引值，看上次你读取到哪里的索引--------------
    # 加载生成的食品数据
    while len(foodStoreData) == 0 and indexFileData < len(indicesStyle1):
        x = indicesStyle1[indexFileData]
        print(f"加载{fileNamePrefix}{x}文件")
        with open(f'../foodJsonData/{fileNamePrefix}{x}.json', 'r', encoding='UTF-8') as f:
            foodStoreData = json.load(f)
        indexFileData = indexFileData + 1
    if len(foodStoreData) == 0 and indexFileData >= len(indicesStyle1):
        lastRowIndex = row_index
        break
    if len(foodStoreData) == 0:
        lastRowIndex = row_index
        break
    # print('1')
    # if row_index % 5 == 0:
    #     foodStoreData = []
    row_data = dataInter.iloc[row_index]
    itemID = row_data['itemID']
    rating = row_data['rating']

    urlItemSave = 'http://127.0.0.1:8080/api/admin/store/product/save'
    urlCommentSave = 'http://127.0.0.1:8080/api/admin/store/product/reply/save'
    # headers = {'Authorization': PEXELS_API_KEY}
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.188 Safari/537.36 CrKey/1.54.250320',
        'Authori-Zation': '1acab8b6ee6c4b899de0f8256d7625fd',
        'Content-Type': 'application/json'
    }
    #       评分数据
    jsonComment = '{ "avatar": "http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/3316070ce6bb49aab05776cd21d91b21pra6fxiblz.png", "comment": "comment", "nickname": "comment", "pics": "[\\"http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/b73c648fb7fd45cf8782e4ca0bc28a42s2a8dpad2x.png\\"]", "productId": 8, "productScore": 4, "serviceScore": 4, "sku": "默认" }'
    productComment = json.loads(jsonComment)
    productComment['productScore'] = rating
    productComment['serviceScore'] = rating
    productComment['productId'] = itemID
    productComment['comment'] = fake.paragraph()
    productComment['nickname'] = fake.word()
    productComment = json.dumps(productComment)

    isExist = foodDao.selectById(itemId=itemID)  # 商品是否已经插入 已经插入则直插入评分
    if not isExist:
        storeProduct = foodStoreData.pop()  # pop一个data数据进行插入
        storeProduct['id'] = itemID  # 指定ID
        storeProduct['storeName'] = storeProduct['storeName'] + str(itemID)  # 担心名称重复可以加入这个 对于后面随机生成的数据来讲--------------------------------

        # 将JSON数据转换为字符串
        storeProduct = json.dumps(storeProduct)

        # 插入Item-------------------
        response = requests.post(urlItemSave, data=storeProduct, headers=headers)
        if response.status_code == 200:
            data = response.json()
            # print(data)
            if data['code'] == 200:
                print(f"插入item{itemID}成功")

                # 插入item评分*******************
                response = requests.post(urlCommentSave, data=productComment, headers=headers)
                if response.status_code == 200:
                    data = response.json()
                    # print(data)
                    if data['code'] == 200:
                        print(f"插入item{itemID}评论评分成功")
                    else:
                        errorProductCommentList.append(itemID)
                else:
                    errorProductCommentList.append(itemID)
                # 评分*******************

            else:
                errorProductList.append(itemID)
        else:
            errorProductList.append(itemID)
        # 插入Item-------------------
    #后面发现交互数据 有100000条，全插入数据库我电脑要报废，放弃插入 所以直插入了11256条加护评论数据，就没有插入更多的交互数据了，后面的插入方式一个商品一个交互数据
    # else:
        # 插入item评分*******************
        # response = requests.post(urlCommentSave, data=productComment, headers=headers)
        # if response.status_code == 200:
        #     data = response.json()
        #     # print(data)
        #     if data['code'] == 200:
        #         print(f"插入item{itemID}评论评分成功")
        #     else:
        #         errorProductCommentList.append(itemID)
        # else:
        #     errorProductCommentList.append(itemID)
        # 评分*******************

print('++++++++++++++++++++++++++++++++')
print("插入最终结果：foodItem插入失败的itemID：")
print(errorProductList)
print("插入最终结果：foodItemComment 评分插入失败的itemID：")
print(errorProductCommentList)
print(f"读取交互数据到索引为{lastRowIndex}")
print(f'当前读取到文件索引{indexFileData}')
re = {
    '数据文件前缀': fileNamePrefix,
    '数据文件索引': indicesStyle1,
    'foodItem插入失败的itemID': errorProductList,
    'foodItemComment 评分插入失败的itemID': errorProductCommentList,
    '读取交互数据到索引为': lastRowIndex,
    '当前读取到文件索引': indexFileData
}
# 数据库出错了，
with open('./insetResult2_' + fileNamePrefix + '.json', 'w', encoding='utf-8') as f:
    json.dump(re, f, ensure_ascii=False, indent=4)
# # 获取第5行数据，行索引号为4
# row_index = 99999
# row_data = data.iloc[row_index]
# # 打印第5行数据
# print(type(row_data))
# print(row_data)
# print(row_data['userID'])

#它大爷的 后面发现其实它的电影ID就是1-1682 所以干脆直接插入电影就好了，，压根不需要读取交互文件  操他吗的、日 浪费老子电脑何时间
